package cn.zlb.frame.common.event;

import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

/**
 * @author yangjie.deng@resico.cn
 * @date 2023-11-09 14:47:46
 * @describe class responsibility
 */
@Slf4j
@Service
public class EvenPublisher {
    private static final long DELAY_TIME_OUT = 3000;
    @Resource
    private RocketMQTemplate template;

    /**
     *   正常消息发送
     *
     * @param topic  主题名称
     * @param event  事件信息
     * @param <E>    事件类型
     */
    public <E extends BaseEvent> void send(String topic, E event) {
        final SendResult sendResult = template.syncSend(topic, event);
        log.info("Normal消息:: 发送结果: {}", sendResult.getSendStatus());
    }

    /**
     *  顺序消息发送
     *
     * @param topic  主题名称
     * @param event  事件信息
     * @param <E>    事件类型
     */
    public <E extends BaseEvent> void sendOrderly(String topic, E event) {
        final SendResult sendResult = template.syncSendOrderly(topic, event, event.getHashKey());
        log.info("Orderly消息:: 发送结果: {}", sendResult.getSendStatus());
    }

    /**
     *  延迟消息发送
     *
     * @param topic  主题名称
     * @param event  事件信息
     * @param <E>    事件类型
     */
    public <E extends BaseEvent> void sendDelay(String topic, E event) {
        Message<E> message = new GenericMessage<>(event);
        final SendResult sendResult = template.syncSend(topic, message, DELAY_TIME_OUT, event.getDelayLevel());
        log.info("Delay消息:: 发送结果: {}", sendResult.getSendStatus());
    }
}
